<template>
  <div class="article-detail">
    <div class="content-wrapper">
      <!-- 左侧文章详情 -->
      <div class="article-content">
        <h2>文章详情</h2>
        <div v-if="article">
          <el-card class="article-card">
            <h3 class="article-title">{{ article.title }}</h3>
            <p class="article-meta"><strong>分类:</strong> {{ article.category }}</p>
            <p class="article-meta"><strong>标签:</strong> {{ article.tags }}</p>
            <p class="article-meta">
              <strong>封面图片:</strong>
              <a :href="article.attachment_url" target="_blank">查看附件</a>
            </p>
            <div class="attachment-section">
              <p class="article-meta"><strong>附件:</strong></p>
              <div v-if="attachments.length === 1">
                <a :href="attachments[0].url" target="_blank">{{ attachments[0].name }}</a>
              </div>
              <ul v-else-if="attachments.length > 1">
                <li v-for="attachment in attachments" :key="attachment.id">
                  <a :href="attachment.url" target="_blank">{{ attachment.name }}</a>
                </li>
              </ul>
              <p v-else>无附件</p>
            </div>
            <p class="article-meta"><strong>浏览量:</strong> {{ article.views }}</p>
            <p class="article-meta"><strong>点赞数:</strong> {{ article.likes }}</p>
            <p class="article-meta"><strong>收藏数:</strong> {{ article.favorites }}</p>
            <p class="article-meta"><strong>创建时间:</strong> {{ article.created_at }}</p>
            <p class="article-meta"><strong>更新时间:</strong> {{ article.updated_at }}</p>
            <div class="article-content-text" v-html="article.content"></div>

            <!-- 点赞和收藏按钮 -->
            <div class="action-buttons">
              <el-button @click="likeArticle" type="primary" :disabled="liked">点赞</el-button>
              <el-button @click="favoriteArticle" type="success" :disabled="favorited">收藏</el-button>
            </div>
          </el-card>

          <div class="comments-section">
            <h3>评论</h3>
            <!-- 使用递归组件 -->
            <CommentItem
              v-for="comment in comments"
              :key="comment.ID"
              :comment="comment"
              @reply="handleNestedReply"
            />

            <!-- 顶级评论输入框 -->
            <el-input
              type="textarea"
              placeholder="写下你的评论..."
              v-model="newComment"
              rows="3"
              class="comment-input"
            ></el-input>
            <el-button @click="submitComment" type="primary" class="comment-submit">提交评论</el-button>
          </div>

          <!-- 动画提示 -->
          <transition name="fade">
            <div v-if="showLikeMessage" class="like-message">点赞成功！</div>
          </transition>
          <transition name="fade">
            <div v-if="showFavoriteMessage" class="favorite-message">已收藏</div>
          </transition>
        </div>
        <div v-else>
          <p>加载文章失败，未能找到文章详情。</p>
        </div>
      </div>

      <!-- 右侧侧边栏 -->
      <div class="sidebar">
        <div class="qr-code">
          <h4>扫描二维码</h4>
          <img :src="qrCodeUrl" alt="QR Code">
        </div>
        <div class="article-link">
          <h4>文章链接</h4>
          <p>{{ articleLink }}</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from "axios";
import QRCode from "qrcode";
import CommentItem from "./CommentItem.vue";

export default {
  components: {
    CommentItem,
  },
  data() {
    return {
      article: null,
      attachments: [],
      qrCodeUrl: "",
      liked: false,
      favorited: false,
      likes: 0,
      favorites: 0,
      showLikeMessage: false,
      showFavoriteMessage: false,
      comments: [],
      newComment: "",
    };
  },
  computed: {
    articleLink() {
      return window.location.href;
    },
  },
  mounted() {
    this.loadArticleDetails();
    this.loadComments();
  },
  methods: {
    async loadArticleDetails() {
      const articleId = this.$route.params.id;
      try {
        const articleResponse = await axios.get(`http://localhost:9090/posts/${articleId}`);
        this.article = articleResponse.data.data;
        this.likes = this.article.likes;
        this.favorites = this.article.favorites;
        const attachmentsResponse = await axios.get(`http://localhost:9090/attachments/${articleId}`);
        this.attachments = attachmentsResponse.data.data.map(a => ({
          id: a.ID,
          name: a.file_name,
          url: a.file_path
        }));
        this.generateQRCode();
      } catch (error) {
        console.error("加载文章或附件失败", error);
      }
    },
    generateQRCode() {
      QRCode.toDataURL(this.articleLink)
        .then((url) => {
          this.qrCodeUrl = url;
        })
        .catch((err) => {
          console.error("生成二维码失败", err);
        });
    },
    async loadComments() {
      const articleId = this.$route.params.id;
      try {
        const response = await axios.get(`http://localhost:9090/comments/${articleId}`);
        this.comments = response.data.data;
      } catch (error) {
        console.error("加载评论失败", error);
      }
    },
    async submitComment() {
      if (!this.newComment.trim()) {
        alert("评论内容不能为空！");
        return;
      }
      const articleId = this.$route.params.id;
      try {
        const token = localStorage.getItem("token");
        if (!token) {
          alert("用户未登录，请先登录！");
          return;
        }
        await axios.post(
          "http://localhost:9090/comments",
          {
            post_id: Number(articleId),
            content: this.newComment,
          },
          {
            headers: {
              Authorization: `${token}`,
            },
          }
        );
        this.newComment = "";
        this.loadComments();
        alert("评论提交成功！");
      } catch (error) {
        console.error("提交评论失败", error);
        alert("提交评论失败！");
      }
    },
    async likeArticle() {
      if (this.liked || this.likes >= 10) {
        return;
      }
      const articleId = this.$route.params.id;
      try {
        await axios.put(`http://localhost:9090/posts/${articleId}/like`);
        this.likes += 1;
        this.liked = true;
        this.showLikeMessage = true;
        setTimeout(() => {
          this.showLikeMessage = false;
        }, 2000);
      } catch (error) {
        console.error("点赞失败", error);
      }
    },
    async favoriteArticle() {
      if (this.favorited) {
        return;
      }
      const articleId = this.$route.params.id;
      const token = localStorage.getItem("token");
      if (!token) {
        alert("用户未登录，请先登录！");
        return;
      }
      try {
        await axios.put(
          `http://localhost:9090/posts/${articleId}/favorite`, 
          {},
          {
            headers: {
              Authorization: `${token}`,
            },
          }
        );
        this.favorites += 1;
        this.favorited = true;
        this.showFavoriteMessage = true;
        setTimeout(() => {
          this.showFavoriteMessage = false;
        }, 2000);
      } catch (error) {
        console.error("收藏失败", error);
        alert("收藏失败！请检查登录状态。");
      }
    },
    async handleNestedReply({ parentId, content }) {
      if (!content.trim()) {
        alert("回复内容不能为空！");
        return;
      }
      const token = localStorage.getItem("token");
      if (!token) {
        alert("请先登录！");
        return;
      }
      try {
        const articleId = this.$route.params.id;
        await axios.post(
          `http://localhost:9090/comments`,
          {
            parent_id: parentId,
            post_id: Number(articleId),
            content,
          },
          {
            headers: {
              Authorization: `${token}`,
            },
          }
        );
        this.loadComments();
      } catch (error) {
        console.error("提交回复失败", error);
      }
    },
  },
};
</script>

<style scoped>
/* 全局基础样式 */
* {
  box-sizing: border-box;
}
body {
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  background-color: #f8f9fa;
  color: #333;
}

/* 文章详情页面 */
.article-detail {
  margin: 20px auto;
  max-width: 1200px;
  padding: 20px;
}

/* 布局 */
.content-wrapper {
  display: flex;
  gap: 20px;
}

/* 文章内容区 */
.article-content {
  flex: 3;
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}
.article-content h2 {
  font-size: 28px;
  margin-bottom: 20px;
  border-bottom: 2px solid #409EFF;
  padding-bottom: 10px;
}

/* 卡片内容 */
.article-card {
  margin-bottom: 30px;
}
.article-title {
  font-size: 24px;
  margin-bottom: 15px;
  color: #2c3e50;
}
.article-meta {
  font-size: 14px;
  color: #666;
  margin: 8px 0;
}
.article-content-text {
  font-size: 16px;
  line-height: 1.8;
  margin-top: 20px;
}

/* 操作按钮 */
.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 15px;
}

/* 评论区域 */
.comments-section {
  margin-top: 40px;
  background: #fefefe;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}
.comment-input {
  margin-top: 15px;
}
.comment-submit {
  margin-top: 10px;
}

/* 侧边栏 */
.sidebar {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.05);
}
.sidebar h4 {
  text-align: center;
  margin-bottom: 15px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}
.qr-code img {
  display: block;
  margin: 0 auto;
  width: 100%;
  max-width: 150px;
}
.article-link {
  margin-top: 20px;
}
.article-link p {
  word-wrap: break-word;
  white-space: normal;
  font-size: 14px;
  color: #007BFF;
}

/* 动画效果 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter, .fade-leave-to {
  opacity: 0;
}
.like-message, .favorite-message {
  color: #fff;
  background-color: #4CAF50;
  padding: 10px 15px;
  border-radius: 5px;
  position: fixed;
  top: 20px;
  right: 20px;
  font-size: 16px;
}

/* 附件列表 */
.attachment-section ul {
  list-style-type: none;
  padding-left: 0;
}
.attachment-section li {
  margin: 5px 0;
}
.attachment-section a {
  text-decoration: none;
  color: #409EFF;
}
.attachment-section a:hover {
  text-decoration: underline;
}
</style>
